#include <p16F887.inc>
	__CONFIG    _CONFIG1, _LVP_OFF & _FCMEN_OFF & _IESO_OFF & _BOR_OFF & _CPD_OFF & _CP_OFF & _MCLRE_OFF & _PWRTE_ON & _WDT_OFF & _INTRC_OSC_NOCLKOUT
	__CONFIG    _CONFIG2, _WRT_OFF & _BOR21V

     cblock     0x20
Delay               ; Assign an address to label Delay1
;Display             ; define a variable to hold the diplay
LastStableState     ; keep track of switch state (open-1; closed-0)
Counter
     endc

     org 0
Start:
     bsf       STATUS,RP0          ; select Register Bank 1
    ; movlw     0xFF
    ; movwf     TRISA               ; Make PortA all input
     clrf      TRISD               ; Make PortD all output
     movlw     0x01
     movwf     TRISB               ; Make RBO pin input (switch)
     bsf       STATUS,RP1          ; select Register Bank 3
    ; movlw     0x1F
    ; movwf     ANSEL               ; PortA pins are all analog, PortE pins are digital
     movlw     0x00
     movwf     ANSELH              ; PortB pins are digitial (important as RB0 is switch)
     bcf       STATUS,RP0          ; address Register Bank 0
     bcf       STATUS,RP1
     clrf      PORTD               ; init LEDs to all off

     ;clrf      Display
     movlw     1
     movwf     LastStableState     ; Assume the Switch is up.
     clrf      Counter
MainLoop:
     btfsc     LastStableState,0
     goto      LookingForUp
LookingForDown:
     clrw                          ; assume it's not, so clear
     btfss     PORTB,0             ; wait for switch to go low
     incf      Counter,w           ; if it's low, bump the counter
     movwf     Counter             ; store either the 0 or incremented value
     goto      EndDebounce

LookingForUp:
     clrw                          ; assume it's not, so clear
     btfsc     PORTB,0             ; wait for switch to go low
     incf      Counter,w
     movwf     Counter

EndDebounce:
     movf      Counter,w           ; have we seen 5 in a row?
     xorlw     5
     btfss     STATUS,Z
     goto      Delay1mS

     comf      LastStableState,f   ; after 5 straight, reverse the direction
     clrf      Counter
     btfss     LastStableState,0   ; Was it a key-down press?
     goto      Delay1mS            ; no: take no action

     incf      PORTD,f           ; if it's the down direction,
    ; movf      Display,w           ; take action on the switch
    ; movwf     PORTD               ; (increment counter and put on display)

Delay1mS:
     movlw     .71                 ; delay ~1000uS
     movwf     Delay
     decfsz    Delay,f             ; this loop does 215 cycles
     goto      $-1
     decfsz    Delay,f             ; This loop does 786 cycles
     goto      $-1
     goto      MainLoop
     end